﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
//using System.Threading.Tasks;
using System.Windows.Forms;
//using NLog;
using Ude;
using Ude.Core;
using System.Configuration;

namespace HyperlinkTagEditor.App
{
    public partial class Form1 : Form
    {

       
        public List<String> IncludeUrls
        {
            get
            {
                return listBox_IncludeUrls.Items.OfType<String>().ToList();
            }

        }
        public List<String> ExcludeUrls
        {
            get
            {
                return listBox_ExcludeUrls.Items.OfType<String>().ToList();
            }
        }


        public Hashtable UserParameters
        {
            get
            {
                Hashtable hs = new Hashtable();
                for (int i = 0; i < listViewRules.Items.Count; i++)
                {
                    //if (i >= 1)
                    {
                        string key = listViewRules.Items[i].Text.ToString();
                        string value = listViewRules.Items[i].SubItems[1].Text.ToString();
                        hs.Add(key, value);
                    }

                }
                return hs;
            }
        }

        public Form1()
        {
            InitializeComponent();


            // Add Default Rules

        }


        
        private void Form1_Load(object sender, EventArgs e)
        {
            InitializeRules();
        }

        private void InitializeRules()
        {
            //Remove all Items
            listViewRules.Items.Clear();
            listViewRules.Columns.Add("Keyword (If KEYWORD below is found in URL)", 70);
            listViewRules.Columns.Add("Text ( Change PARAMETER to…) ", 100);
           

            //Add Default Items
            //{
            //    ListViewItem listitem = new ListViewItem("?");
            //    // listitem.SubItems.Add("REPLACE_FIRST_CHARACTER_FOUND");
            //    listitem.SubItems.Add("&");
            //    //listitem.SubItems.Add("BOTH");
            //    listViewRules.Items.Add(listitem);
            //}
            //{
            //    ListViewItem listitem = new ListViewItem("cancel");
            //    // listitem.SubItems.Add("REPLACE_FIRST_CHARACTER_FOUND");
            //    listitem.SubItems.Add("");
            //    //listitem.SubItems.Add("BOTH");
            //    listViewRules.Items.Add(listitem);
            //}

            //{
            //    ListViewItem listitem = new ListViewItem("contact");
            //    // listitem.SubItems.Add("REPLACE_FIRST_CHARACTER_FOUND");
            //    listitem.SubItems.Add("?contact_email=abc@xyz.com");
            //    //listitem.SubItems.Add("BOTH");
            //    listViewRules.Items.Add(listitem);
            //}

            //{
            //    ListViewItem listitem = new ListViewItem("news");
            //    // listitem.SubItems.Add("REPLACE_FIRST_CHARACTER_FOUND");
            //    listitem.SubItems.Add("?news_online=1");
            //    //listitem.SubItems.Add("BOTH");
            //    listViewRules.Items.Add(listitem);
            //}

            try
            {
                String configFile = Application.StartupPath + "\\appconfig.hteconfig";
                DataSet ds = new DataSet();
                ds.ReadXml(configFile, XmlReadMode.ReadSchema);
                LoadAllData(ds);
            }
            catch (Exception ex)
            {

            }
            
        }

        private void btnAddRule_Click(object sender, EventArgs e)
        {
            if (btnAddRule.Text.Contains("Save"))
            {
                AddNewRule(txtRuleKeyword.Text, txtRuleText.Text);
                EnableEditControls(false);

                txtRuleKeyword.Text = "";
                txtRuleText.Text = "";

                btnAddRule.Text = btnAddRule.Text.Replace("Save", "Add");
            }
            else if (btnAddRule.Text.Contains("Add"))
            {
                EnableEditControls(true);

                btnAddRule.Text = btnAddRule.Text.Replace("Add", "Save");
            }
        }

        private void EnableEditControls(bool isEnabled)
        {
            txtRuleKeyword.Enabled = isEnabled;
           
            txtRuleText.Enabled = isEnabled;
            listViewRules.Enabled = !isEnabled; ;
        }

        private void AddNewRule(string keyWord, string text = "")
        {

            if (String.IsNullOrEmpty(keyWord))
                return;

            //if (keyWord.Trim().ToLower() == "cancel" || keyWord.Trim().ToLower() == "?")
            if ( keyWord.Trim().ToLower() == "?")
                return;
            
            ListViewItem listitem = new ListViewItem(keyWord);
            listitem.SubItems.Add(text);

            if ( !UserParameters.Contains(keyWord)  )
                listViewRules.Items.Add(listitem);


        }

       

        private void btnEditRule_Click(object sender, EventArgs e)
        {
            if (btnEditRule.Text.Contains("Edit"))
            {
                EnableEditControls(true);
                btnEditRule.Text = btnEditRule.Text.Replace("Edit", "Save");
            }
            else if (btnEditRule.Text.Contains("Save"))
            {
                if (listViewRules.SelectedItems.Count > 0)
                {
                    ListViewItem item = listViewRules.SelectedItems[0];
                    RemoveRuleFromListView(item);
                }
                AddNewRule(txtRuleKeyword.Text,  txtRuleText.Text);
                btnEditRule.Text = btnEditRule.Text.Replace("Save", "Edit");
                EnableEditControls(false);
                txtRuleKeyword.Text = "";
                txtRuleText.Text = "";
            }
        }

        private void RemoveRuleFromListView(ListViewItem item)
        {
            listViewRules.Items.Remove(item);
        }

        private void listViewRules_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            
            // Donot remove the 1st and 2nd rule
            //if( listViewRules.SelectedIndices.Contains(0) || listViewRules.SelectedIndices.Contains(1))
            //{
            //    btnEditRule.Enabled = false;
            //    btnRemoveRule.Enabled = false;
            //}
            //else
            //{
                btnEditRule.Enabled = true;
                btnRemoveRule.Enabled = true;
            //}



            // On Item Selection Show the Items in the TextBox
            if (listViewRules.SelectedItems.Count > 0)
            {
                ListViewItem item = listViewRules.SelectedItems[0]; // Only 1 row is allowed to be selected
                UpdateRuleIntoEditor(item);
            }
        }

        private void UpdateRuleIntoEditor(ListViewItem item)
        {
            if (item != null)
            {
                txtRuleKeyword.Text = item.Text;
                txtRuleText.Text = item.SubItems[1].Text;
            }

            
        }

        private void btnRemoveRule_Click(object sender, EventArgs e)
        {
            if (listViewRules.SelectedItems.Count > 0)
            {
                ListViewItem item = listViewRules.SelectedItems[0];
                RemoveRuleFromListView(item);
            }
        }

        private void ApplyRuleOnSample()
        {
            //string parameter = txtParameter.Text;
            //string sampleInput = txtSampleInput.Text;
            //string keyWord = txtRuleKeyword.Text;
            //ActionType selectedAction = (ActionType)Enum.Parse(typeof(ActionType), comboBoxRuleAction.SelectedItem.ToString());
            //string ruleText = txtRuleText.Text;


            //txtSampleOutput.Text = HyperLinkUrlModifier.ApplyRules(sampleInput, parameter, keyWord, selectedAction, ruleText);

        }

        private void btnRuleApply_Click(object sender, EventArgs e)
        {
            ApplyRuleOnSample();
        }

        private void btnSourceFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Text files (*.txt)|*.txt|Html Files (*.html)|*.html;*.htm";
            openFileDialog.Multiselect = false;
            DialogResult result = openFileDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                txtSourceFile.Text = openFileDialog.FileName;
            }
        }

        private void btnDestFile_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Text files (*.txt)|*.txt|Html Files (*.html)|*.html;*.htm";
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.OverwritePrompt = true;
            DialogResult result = saveFileDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                txtDestFile.Text = saveFileDialog.FileName;
            }


        }

        private void btnGo_Click(object sender, EventArgs e)
        {

            // Read the Input FIle into a string
            // Extracts the Urls from the String
            // Apply Rules to the Urls
            // Update the String
            // Write to the OutPutFile



            // Read the Html/Text File to a String
            String InputFileString = String.Empty;
            String inputFilePath = txtSourceFile.Text;
            listStatus.Items.Add("Reading File: " + inputFilePath);

            CharsetDetector detector = new CharsetDetector();
            using (FileStream fs = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read))
            {
                detector.Feed(fs);
                detector.DataEnd();
            }
            //MessageBox.Show(detector.Charset);
            listStatus.Items.Add("Charset : " + detector.Charset);
            

            Encoding inputTypeEncoding =  Encoding.GetEncoding(detector.Charset); 


            InputFileString = File.ReadAllText(inputFilePath, inputTypeEncoding);

            rtfSource.Text = InputFileString;

            
            string extType = inputFilePath.Substring(inputFilePath.LastIndexOf('.'));
            FileType fileType = ( extType.ToLower().Contains("txt") ? FileType.TEXT : FileType.HTML);

            listStatus.Items.Add("File Extention: " + extType);

            String OutputFileString = InputFileString;
            StringBuilder outputStringBuilder=new StringBuilder();

            OutputFileString=URLUtilities.FindAppyRuleAndThenReplace(InputFileString, fileType, 
                                                                     IncludeUrls, ExcludeUrls, 
                                                                     UserParameters, txtParameter.Text, 
                                                                     listStatus, 
                                                                     ref rtfUrlList,
                                                                     ref rtfUrlRulesApplied);
            rtfFinalResults.Text = OutputFileString;

            File.WriteAllText(txtDestFile.Text, OutputFileString, inputTypeEncoding);

        }

        public Stream GenerateStreamFromString(string s)
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            writer.Write(s);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }

        


        private void btn_AddInlcudeURL_Click(object sender, EventArgs e)
        {
            String item = txt_IncludeURL.Text.ToLower().Trim();
            if (!listBox_IncludeUrls.Items.Contains(item))
            {
                if (!String.IsNullOrEmpty(item))
                {
                    listBox_IncludeUrls.Items.Add(item);
                    txt_IncludeURL.Text = "";
                }
            }
        }

        private void btn_AddExcludeURL_Click(object sender, EventArgs e)
        {
            String item = txt_ExcludeURL.Text.ToLower().Trim();
            
            if (!listBox_ExcludeUrls.Items.Contains(item))
            {
                if (!String.IsNullOrEmpty(item))
                {
                    listBox_ExcludeUrls.Items.Add(item);
                    txt_ExcludeURL.Text = "";
                }
            }
        }

        private void btn_DelIncludeURL_Click(object sender, EventArgs e)
        {
            if (listBox_IncludeUrls.SelectedIndices.Count > 0)
            {
                string itemSelected = listBox_IncludeUrls.SelectedItem.ToString();

                if (MessageBox.Show("Do you want to remove the Selected Url", "Include Url", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    listBox_IncludeUrls.Items.Remove(itemSelected);
                }
            }

        }

        private void btn_DelExcludeURL_Click(object sender, EventArgs e)
        {
            if (listBox_ExcludeUrls.SelectedIndices.Count > 0)
            {
                string itemSelected = listBox_ExcludeUrls.SelectedItem.ToString();

                if (MessageBox.Show("Do you want to remove the Selected Url", "Exclude Url", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    listBox_ExcludeUrls.Items.Remove(itemSelected);
                    txtRuleKeyword.Text = "";
                    txtRuleText.Text = "";
                }
            }
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            // Save the Data to the File extention .hteconfig

            String saveFileName = String.Empty;
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "HyperlinkTagEditor Config files (*.hteconfig)|*.hteconfig";
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.OverwritePrompt = true;
            saveFileDialog.FileName = "appconfig.hteconfig";
            saveFileDialog.InitialDirectory = Application.StartupPath;
            DialogResult result = saveFileDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                saveFileName = saveFileDialog.FileName;
                DataSet saveDs = CreateDefaultSaveDatabase();
                SaveAllData(saveDs, saveFileName);

            }

           


        }

        private void SaveAllData(DataSet saveDs, string saveFileName)
        {
            // Save Rules
            DataTable RulesTable = saveDs.Tables["RulesTable"];

            foreach (ListViewItem item in listViewRules.Items)
            {
                DataRow newRow = RulesTable.NewRow();
                newRow["Keyword"] = item.Text.ToString();
                newRow["Text"] = item.SubItems[1].Text.ToString();
                RulesTable.Rows.Add(newRow);
            }
            RulesTable.AcceptChanges();

            DataTable IncludeUrlsTable = saveDs.Tables["IncludeUrlsTable"];
            foreach (var item in IncludeUrls)
            {
                DataRow newRow = IncludeUrlsTable.NewRow();
                newRow["Url"] = item.ToString();

                IncludeUrlsTable.Rows.Add(newRow);
            }
            IncludeUrlsTable.AcceptChanges();

            DataTable ExcludeTopUrlsTable = saveDs.Tables["ExcludeTopUrlsTable"];
            foreach (var item in ExcludeUrls)
            {
                DataRow newRow = ExcludeTopUrlsTable.NewRow();
                newRow["Url"] = item.ToString();
                ExcludeTopUrlsTable.Rows.Add(newRow);
            }
            ExcludeTopUrlsTable.AcceptChanges();

            DataTable OtherSingleDataTable = saveDs.Tables["OtherSingleDataTable"];
            {
                DataRow newRow = OtherSingleDataTable.NewRow();
                newRow["Type"] = "TopParamater";
                newRow["Text"] = txtParameter.Text;
                OtherSingleDataTable.Rows.Add(newRow);
            }
            {
                DataRow newRow = OtherSingleDataTable.NewRow();
                newRow["Type"] = "SourceFilePath";
                newRow["Text"] = txtSourceFile.Text;
                OtherSingleDataTable.Rows.Add(newRow);
            }
            {
                DataRow newRow = OtherSingleDataTable.NewRow();
                newRow["Type"] = "DestFilePath";
                newRow["Text"] = txtDestFile.Text;
                OtherSingleDataTable.Rows.Add(newRow);
            }
            OtherSingleDataTable.AcceptChanges();



            saveDs.AcceptChanges();

            saveDs.WriteXml(saveFileName, XmlWriteMode.WriteSchema);
        }

        private DataSet CreateDefaultSaveDatabase()
        {
            DataSet ds = new DataSet("HyperlinkTagEditor");

            DataTable RulesTable = new DataTable("RulesTable");
            RulesTable.Columns.Add("Keyword", typeof(String));
            RulesTable.Columns.Add("Text", typeof(string));
            RulesTable.AcceptChanges();

            DataTable IncludeUrlsTable = new DataTable("IncludeUrlsTable");
            IncludeUrlsTable.Columns.Add("Url", typeof(String));
            IncludeUrlsTable.AcceptChanges();

            DataTable ExcludeTopUrlsTable = new DataTable("ExcludeTopUrlsTable");
            ExcludeTopUrlsTable.Columns.Add("Url", typeof(String));
            ExcludeTopUrlsTable.AcceptChanges();

            DataTable OtherSingleDataTable = new DataTable("OtherSingleDataTable");
            OtherSingleDataTable.Columns.Add("Type", typeof(string));
            OtherSingleDataTable.Columns.Add("Text", typeof(string));
            OtherSingleDataTable.AcceptChanges();

            ds.Tables.Add(RulesTable);
            ds.Tables.Add(IncludeUrlsTable);
            ds.Tables.Add(ExcludeTopUrlsTable);
            ds.Tables.Add(OtherSingleDataTable);
            ds.AcceptChanges();

            return ds;



        }

        private void btn_Load_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "HyperlinkTagEditor Config files (*.hteconfig)|*.hteconfig";
            openFileDialog.Multiselect = false;
            DialogResult result = openFileDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                String openFileName = openFileDialog.FileName;
                DataSet ds = new DataSet();
                ds.ReadXml(openFileName, XmlReadMode.ReadSchema);
                LoadAllData(ds);

            }
            
        }

        private void LoadAllData(DataSet ds)
        {

            DataTable RulesTable = ds.Tables["RulesTable"];
            listViewRules.Items.Clear();
            foreach (DataRow row in RulesTable.Rows)
            {
                ListViewItem listitem = new ListViewItem(row["Keyword"].ToString());
                listitem.SubItems.Add(row["Text"].ToString());
                listViewRules.Items.Add(listitem);
            }


            DataTable IncludeUrlsTable = ds.Tables["IncludeUrlsTable"];
            listBox_IncludeUrls.Items.Clear();
            foreach (DataRow row in IncludeUrlsTable.Rows)
            {
                //ListViewItem listitem = new ListViewItem(row["Url"].ToString());
                listBox_IncludeUrls.Items.Add(row["Url"].ToString());
            }

            

            DataTable ExcludeTopUrlsTable = ds.Tables["ExcludeTopUrlsTable"];
            listBox_ExcludeUrls.Items.Clear();
            foreach (DataRow row in ExcludeTopUrlsTable.Rows)
            {
                //ListViewItem listitem = new ListViewItem(row["Url"].ToString());
                listBox_ExcludeUrls.Items.Add(row["Url"].ToString());
            }
            

            DataTable OtherSingleDataTable = ds.Tables["OtherSingleDataTable"];
            foreach (DataRow row in OtherSingleDataTable.Rows)
            {
                String Type = row["Type"].ToString();
                String Text = row["Text"].ToString();
                if (Type == "TopParamater")
                {
                    txtParameter.Text = Text;
                }
                if (Type == "SourceFilePath")
                {
                    txtSourceFile.Text = Text;
                }
                if (Type == "DestFilePath")
                {
                    txtDestFile.Text = Text;
                }
            }

          
        }

        
    }
    
}
